<template>
  <div class="app-container">
    <el-form ref="goodsInventoryAddForm" :model="goodsInventoryAddForm" :rules="goodsInventoryAddFormRule"
             label-width="100px" >
      <h3 style="width: 100%;">盘点单</h3>
      <el-row>
        <el-col :span="6">
          <el-form-item label="盘点编号" prop="sn">
            <el-input v-model="goodsInventoryAddForm.sn" ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="2">
          <el-form-item label-width="80">
            <el-switch v-model="autoGenFlag"
                       active-color="#13ce66"
                       active-text="自动生成"
                       @change="handleAutoGenChange(autoGenFlag)" >
            </el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点时间" prop="inventoryTime">
            <el-date-picker v-model="goodsInventoryAddForm.inventoryTime" value-format="timestamp" type="date" style="width: 100%"
                             placeholder="选择日期时间">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点人" prop="inventoryPerson">
            <el-input v-model="goodsInventoryAddForm.inventoryPerson" :disabled="true" placeholder="请选择盘点人" >
              <el-button slot="append" @click="handleUserSelect"  icon="el-icon-search"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="仓库" prop="warehouseId">
            <el-cascader v-model="warehouseInfo"  ref="selectck"
                         :options="warehouseOptions"
                         :props="warehouseProps"
                         :style="{width: '100%'}"
                         @change="handleWarehouseChanged"
            >
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="盘点状态" prop="status" >
            <el-input v-model="goodsInventoryAddForm.status" :disabled="true"  value="0"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="goodsInventoryAddForm.inventoryDesc" type="textarea" placeholder="请输入备注"  maxlength="250"/>
          </el-form-item>
        </el-col>
      </el-row>

      <div class="mx">

        <h3>物料明细</h3>
        <el-button class="button"  type="primary" v-if="type !== 'detail'"
                   @click="handleSelectWarehouseEntryBatch">添加物料</el-button>
      </div>
      <ItemSelect ref="itemSelect" @onSelected="onItemSelected" > </ItemSelect>
<!--      <div class="prolist" >-->
        <el-form-item style="width: 100%;" class="aa">
          <el-table :data="goodsInventoryAddForm.productList" border :cell-style="{ textAlign: 'center' }"
                    :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
            <el-table-column label="序号"
              type="index"
              width="50">
            </el-table-column>
            <el-table-column label="商品编号" align="center" prop="itemCode">
              <template slot-scope="scope">
                {{ scope.row.itemCode }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称" align="center" prop="itemName">
              <template slot-scope="scope">
                {{ scope.row.itemName }}
              </template>
            </el-table-column>
            <el-table-column label="规格型号" align="center" prop="unitOfMeasure">
              <template slot-scope="scope">
                {{ scope.row.specification }}
              </template>
            </el-table-column>
            <el-table-column label="单位" align="center" prop="unitOfMeasure">
              <template slot-scope="scope">
                {{ scope.row.unitOfMeasure }}
              </template>
            </el-table-column>
            <el-table-column label="品牌" align="center" prop="itemBrand">
              <template slot-scope="scope">
                {{ scope.row.unitOfMeasure }}
              </template>
            </el-table-column>
            <el-table-column label="颜色" align="center" prop="itemColor">
              <template slot-scope="scope">
                {{ scope.row.itemColor }}
              </template>
            </el-table-column>
            <el-table-column label="技术要求" align="center" prop="itemTechReq">
              <template slot-scope="scope">
                {{ scope.row.itemTechReq }}
              </template>
            </el-table-column>
            <el-table-column label="型号" align="center" prop="itemModel">
              <template slot-scope="scope">
                {{ scope.row.itemModel }}
              </template>
            </el-table-column>

            <el-table-column label="库存数量" align="center" prop="quantityOnhand">
              <template slot-scope="scope">
                {{scope.row.quantityOnhand}}
              </template>
            </el-table-column>
            <el-table-column label="盘点数量" align="center" prop="inventoryNum">
              <template slot-scope="scope">
                <el-input  type="number" :min="0" :maxlength="90000000000" size="mini" style="width:100px"  @change="handleEdit(scope.$index, scope.row)"
                           v-model="scope.row.inventoryNum"  :disabled="type === 'detail' || type === 'audit'"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="差异" align="center" prop="diffNum">
              <template slot-scope="scope">
<!--                {{ scope.row.inventory_num - scope.row.remain_num || 0 }}-->
                  <el-input  v-model="scope.row.diffNum" placeholder="差异" size="mini" style="width:100px" readonly="readonly"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="分类名称" align="center" prop="itemTypeName">
              <template slot-scope="scope">
                {{ scope.row.itemTypeName }}
              </template>
            </el-table-column>
            <el-table-column label="备注" align="center" prop="remark">
              <template slot-scope="scope">
                <el-input v-model="scope.row.remark" :min="0" :maxlength="20" ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" v-if="type !== 'detail' && type !== 'audit'">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                           @click="goodsInventoryAddForm.productList.splice(scope.$index, 1)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
<!--      </div>-->
    </el-form>
<!--    <div class="footer">
      <el-button v-if="type === 'audit' && type !== 'detail'" type="primary" @click="handlePassGoodsInventory()">审核通过
      </el-button>
      <el-button v-if="type === 'audit' && type !== 'detail'" type="danger" @click="dialogVisible = true">审核驳回
      </el-button>
      <el-button v-if="type !== 'audit' && type !== 'detail'" type="primary" @click="submitGoodsInventoryAddForm">保存
      </el-button>
      <el-button @click="cancel">返回
      </el-button>
    </div>-->
    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="submitGoodsInventoryAddForm">保存</el-button>
      <el-button type="primary" @click="cancel">返 回</el-button>
    </div>

<!--    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <el-form ref="goodsInventoryAddForm" :model="goodsInventoryAddForm" label-width="120px" inline style="width:900px">
        <el-form-item label="驳回原因" prop="reject_reason" required="true">
          <el-input v-model="goodsInventoryAddForm.reject_reason" type="textarea" :minlength="0"
                    :maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRejectGoodsInventory()">确 定</el-button>
      </span>
    </el-dialog>-->
    <UserSingleSelect ref="userSelect" @onSelected="onUserSelected"></UserSingleSelect>
  </div>
</template>

<script>

import $ from 'jquery';
import {getTreeList} from "@/api/mes/wm/warehouse";
import ItemSelect  from "@/components/itemSelect/multi.vue";
import {addPandian, updatePandian} from "@/api/mes/wm/pandian";
import UserSingleSelect from "@/components/userSelect/single.vue"
import {genCode} from "@/api/system/autocode/rule";
export default {
  name: 'goodsInventoryAdd',
  components: {UserSingleSelect, ItemSelect},
  data() {
    return {
      //自动生成编码
      autoGenFlag:false,
      warehouseInfo:[],
      warehouseOptions:[],
      warehouseProps:{
        multiple: false,
        value: 'pId',
        label: 'pName',
      },
      adminList: [],
      dialogVisible: false,
      warehouseList: [],
      deptList: [],
      deptListAll: [],
      id: '',
      type: '',
      /** 出库单表单*/
      goodsInventoryAddForm: {
        status:'盘点中',
        productList: []
      },
      /** 校验规则 */
      goodsInventoryAddFormRule: {
        sn: [
          { required: true, message: '盘点单编号不能为空', trigger: 'blur' }
        ],
        inventoryTime: [
          { required: true, message: '盘点时间不能为空', trigger: 'blur' }
        ],
        inventoryPerson:[
          { required: true, message: '盘点人不能为空', trigger: 'blur' }
        ],
        warehouseId:[
          { required: true, message: '仓库不能为空', trigger: 'blur' }
        ]

      },
      warehouseProduct: null
    };
  },
  created() {
    // this.getList();

    this.getWarehouseList();

  },
  methods: {
    //自动生成编码
    handleAutoGenChange(autoGenFlag){
      if(autoGenFlag){
        genCode('PANDIAN_CODE').then(response =>{
          this.goodsInventoryAddForm.sn = response;
          this.$forceUpdate()
        });
      }else{
        this.goodsInventoryAddForm.sn = null;
        this.$forceUpdate()
      }
      this.$forceUpdate()
    },
    //点击人员选择按钮
    handleUserSelect(){
      this.$refs.userSelect.showFlag = true;
    },
    //人员选择返回
    onUserSelected(row){
      this.goodsInventoryAddForm.inventoryPerson= row.nickName;
      this.goodsInventoryAddForm.inventoryPersonId= row.userId;
      this.$forceUpdate()
    },
    /** 提交按钮 */
    submitGoodsInventoryAddForm() {
      this.$refs["goodsInventoryAddForm"].validate(valid => {
        if (valid) {

            addPandian(this.goodsInventoryAddForm).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              localStorage.setItem("IndexRefresh", true);
              this.$store.dispatch("tagsView/delView", this.$route)
              // this.$router.push({path: '/pandian/pandian'});
              this.$router.go(-1)
            });

        }else{
          return
        }
      });
      this.open = false;

    },
    // 取消按钮
    cancel() {
      localStorage.setItem("IndexRefresh", true);
      // 调用全局挂载的方法，关闭当前页
      this.$store.dispatch("tagsView/delView", this.$route)
      this.$router.go(-1)
    },
    //商品差
    handleEdit(index, row) {

      console.log("计算row",row)
      console.log(Number(row.inventoryNum))
      console.log(Number(row.quantityOnhand))
      if( row.inventoryNum){
        row.diffNum = parseFloat(Number(row.inventoryNum)-Number(row.quantityOnhand)).toFixed(2)
        // row.diffNum = Number(row.inventoryNum) - Number(row.quantityOnhand)
        console.log(row.diffNum)
      }
    },
    // 选择出库单
     handleSelectWarehouseEntryBatch() {

      if (!this.goodsInventoryAddForm.warehouseId) {
        this.$message.error('请先选择仓库！')
        return
      }

      this.$refs.itemSelect.showFlag = true;

    },
    //物料选择弹出框
    onItemSelected(obj){
      if(this.goodsInventoryAddForm.productList.length >0){
        console.log("pppp",this.goodsInventoryAddForm.productList)
        // 看所选物料是否重复
        var commonElements = $.grep(this.goodsInventoryAddForm.productList, function(element) {
          return $.grep(obj, function(el) {
            return el.itemId === element.itemId;
          }).length > 0;
        })
        console.log("duoooooo",commonElements)
        if(commonElements.length > 0){
          this.$message.warning("物料存在重复请重新选择")
          return
        }
        this.goodsInventoryAddForm.productList=this.goodsInventoryAddForm.productList.concat(obj)
      }else{
        //第一次增加
        this.goodsInventoryAddForm.productList=obj
      }

      console.log("ppppp",obj)
      console.log("productListtttt",this.goodsInventoryAddForm.productList)

    },
    //选择默认的仓库、库区、库位
    handleWarehouseChanged(obj){
      console.log("handleWarehouseChanged",obj)
      const selectedNodes = this.$refs.selectck.getCheckedNodes();
      console.log("selectedNodes",selectedNodes)
      console.log('选中的名称11:',selectedNodes[0].pathLabels)
      if(obj !=null){
        this.goodsInventoryAddForm.warehouseId = obj[0];
        this.goodsInventoryAddForm.locationId = obj[1];
        this.goodsInventoryAddForm.areaId = obj[2];
        this.goodsInventoryAddForm.warehouseName=selectedNodes[0].pathLabels[0]
        this.goodsInventoryAddForm.locationName=selectedNodes[0].pathLabels[1]
        this.goodsInventoryAddForm.areaName=selectedNodes[0].pathLabels[2]
      }
    },
    getWarehouseList(){
      getTreeList().then( response =>{
        if(response.data){
          this.warehouseOptions = response.data.filter((el) =>{
            return el.warehouseCode.indexOf('VIR') == -1;
          });;
        }
        this.warehouseOptions.map(w =>{
          w.children.map(l =>{
            let lstr =JSON.stringify(l.children).replace(/locationId/g,'lId').replace(/areaId/g, 'pId').replace(/areaName/g,'pName');
            l.children = JSON.parse(lstr);
          });

          let wstr = JSON.stringify(w.children).replace(/warehouseId/g,'wId').replace(/locationId/g, 'pId').replace(/locationName/g,'pName');
          w.children =  JSON.parse(wstr);

        });
        let ostr=JSON.stringify(this.warehouseOptions).replace(/warehouseId/g,'pId').replace(/warehouseName/g, 'pName');
        this.warehouseOptions = JSON.parse(ostr);
        console.log("options",this.warehouseProps)
      });
    },
  }


}
</script>
<style type="text/css" scoped>
.mx{
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: flex-start;
  align-items: center;
  .button {
    margin-left: 10px;
  }
}
.aa >>> .el-form-item__content {
  margin-left:0px !important;
}
</style>

<!--
<style type="text/css" scoped>
.mx{
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: flex-start;
  align-items: center;
  .button {
    margin-left: 10px;
  }
}

/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;
  width: 100%;

  .button {
    margin-left: 10px;
  }

}
.prolist {
  width: 100%;
  display: flex;
  /deep/ {
    .el-form&#45;&#45;inline .el-form-item__content {
      display: flex;
    }
  }
}

/*.change-form {
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  flex-wrap: wrap;
  min-width: 900px;

  .change-form-item {
    width: 100%;
    margin: 0 10px 20px 0;
    display: flex;
    flex-direction: row;
    flex-wrap: nowrap;
  }

  /deep/ {
    .el-form-item__content {
      flex: 1;
      width: 100%;
    }

    .el-date-editor,
    .el-cascader,
    .el-select {
      width: 100%;
    }
  }
}*/

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.goods-info {
  display: flex;

  .goods-name-box {
    text-align: left;

    .goods-name {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 16px;
    }

    .specs {
      color: #999999;
    }
  }
}

/deep/ {
  .el-input&#45;&#45;suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}
</style>
-->
